-- TODO: utilize mySQL database to store variables such as fuel, health and owner

function carEngineToggle(thePlayer)
	if getPedOccupiedVehicle(thePlayer) ~= nil then
		if getVehicleEngineState(getPedOccupiedVehicle(thePlayer)) == true then
			setVehicleEngineState(getPedOccupiedVehicle(thePlayer), false)
		else
			setVehicleEngineState(getPedOccupiedVehicle(thePlayer), true)
		end
	end
end

function carLightsToggle(thePlayer) -- TODO: make this only toggle the front lights
	if getPedOccupiedVehicle(thePlayer) ~= nil then -- TODO: add car ownership and fuel (fuel is only depleted when the engine is on)
		if getVehicleOverrideLights(getPedOccupiedVehicle(thePlayer)) ~= 2 then
			setVehicleOverrideLights(getPedOccupiedVehicle(thePlayer), 2)
		else
			setVehicleOverrideLights(getPedOccupiedVehicle(thePlayer), 1)
		end	
	end
end

function carLockToggle(thePlayer) -- TODO: compare entering player against the vehicle's owner
	if getPedOccupiedVehicle(thePlayer) ~= nil then -- TODO: add lock picking
		if isVehicleLocked(getPedOccupiedVehicle(thePlayer)) == true then
			setVehicleLocked(getPedOccupiedVehicle(thePlayer), false)
			outputChatBox("You have unlocked your vehicle.", thePlayer)
		else
			setVehicleLocked(getPedOccupiedVehicle(thePlayer), true)
			outputChatBox("You have locked your vehicle.", thePlayer)
		end
	end
end

function onExit(theVehicle, leftSeat, jackerPlayer)
	if leftSeat == 0 and not jackerPlayer then
		setVehicleEngineState(theVehicle, false)
	end
end

function onEnter(theVehicle, leftSeat)
	if leftSeat == 0 then -- TODO: compare entering player against the vehicle's owner
		setTimer(setVehicleEngineState, 800, 1, theVehicle, true)
	end
end

function bindCarKeys()
	bindKey(source, "L", "down", carLightsToggle)
end



addCommandHandler("engine", carEngineToggle)
addCommandHandler("lights", carLightsToggle)
addCommandHandler("lock", carLockToggle)
addEventHandler("onPlayerVehicleExit", getRootElement(), onExit)
addEventHandler("onPlayerVehicleEnter", getRootElement(), onEnter)
addEventHandler("onPlayerSpawn", getRootElement(), bindCarKeys)